// +----------------------------------------------------------------------
// | JavaWeb_Cloud_Pro微服务旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2019~2020 南京JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <1175401194@qq.com>
// +----------------------------------------------------------------------

package com.javaweb.common.security.exception;

import com.alibaba.fastjson.JSONObject;
import com.javaweb.common.framework.utils.JsonResult;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authException) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
//        httpServletResponse.setContentType("application/json; charset=utf-8");
//        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Throwable cause = authException.getCause();
        try {
            if (cause instanceof InvalidTokenException) {
                // 无效的token
                JsonResult jsonResult = new JsonResult();
                httpServletResponse.getWriter().write(JSONObject.toJSON(jsonResult.error(401, "请先登录")).toString());
            } else {
                // 访问此资源需要完全的身份验证
                JsonResult jsonResult = new JsonResult();
                httpServletResponse.getWriter().write(JSONObject.toJSON(jsonResult.error(401, "访问此资源需要完全的身份验证")).toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
